import { app, BrowserWindow, ipcMain, nativeTheme, Menu } from 'electron'
// import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

import log from 'electron-log/main';
import fs from 'fs-extra';
import store from './store';
import serve from './serve';

// const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// log
Object.assign(console, log.functions);


// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')
export const EXE_PATH = path.dirname(app.getPath('exe'))
export const APPS_PATH = path.join(app.getPath('userData'), "apps")
export const TEMP_PATH = path.join(app.getPath('userData'), "temp")
export const UPDATER_EXE_PATH = path.join(EXE_PATH, "updater.exe")

fs.emptyDir(TEMP_PATH)
process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null

function createWindow() {
  win = new BrowserWindow({
    // icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    title: "Toy-Kit",
    width: 900,
    height: 600,
    minWidth: 800,
    minHeight: 500,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
    },
  })

  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })

  Menu.setApplicationMenu(null);
  createPreload()
  if (VITE_DEV_SERVER_URL) {
    // win?.webContents.openDevTools()
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

app.whenReady().then(createWindow)

const createPreload = () => {
  ipcMain.on("setStore", (_: any, key: string, obj: any) => {
    switch (key) {
      case "openAtLogin":
        app.setLoginItemSettings({
          openAtLogin: obj,
        });
        break;
      case "theme":
        setTheme(obj)
        break;
    }
    store.set(key, obj);
  })
  ipcMain.handle("getStore", (_: any, key: string) => {
    if (key === "") {
      return store.all()
    } else {
      return store.get(key)
    }
  })
  ipcMain.on("open", openWindow)
  ipcMain.handle("loadData", serve.loadData)
  ipcMain.on("download", serve.download)
  ipcMain.on("upgrade", serve.upgrade)
}

// setTheme
const setTheme = (value: any) => {
  if (!value) {
    value = store.get("theme", "system")
  }
  nativeTheme.themeSource = value
  if (value == 'system') {
    value = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
  }
  let isDark = value === 'dark'
  BrowserWindow.getAllWindows().forEach(item => {
    item.webContents.send('dark', isDark)
  })
}

const openWindow = (_: any, name: string) => {
  let data: any = store.get(`apps.${name}`, {})
  const child = new BrowserWindow({
    title: data.name,
    width: 900,
    height: 600,
    minWidth: 800,
    minHeight: 500,
    show: false,
  })
  child.loadFile(path.join(APPS_PATH, `${data.name}.asar`, 'index.html'))
  child.once('ready-to-show', () => {
    child.show()
  })
}
